# --coding:utf-8--
import uuid
import time
import os
import base64
from fastapi.responses import ORJSONResponse, JSONResponse
from fastapi.routing import APIRouter
from views.spider_test.func.request import *
from views.spider_test.func.utils import *
from views.login.func.model import *
from extensions import *
from extensions.utils import *
from fastapi import File, UploadFile
from starlette.responses import FileResponse
from logs.settings import loggers
from fastapi.responses import StreamingResponse

router = APIRouter(
    prefix="/api",
    tags=["文档数据"],
    default_response_class=ORJSONResponse
)
collection = 'mdData'


@router.post('/md/project', summary='md文档项目列表', description='', )
@login_check
async def ApiPro(request: Request, item: dict):
    try:
        md_level = item.get('level')
        md_parent = item.get('parent')
        result = MonConn.findall(
            'mdpro', {"level": md_level, "parent": md_parent}, sortfield="date")
        result_list = foomatMid(result)

        return {"data": result_list, "msg": "获取文档项目成功"}
    except Exception as e:
        loggers.error(e)
        return {"msg": "error", "detail": str(e)}


@router.post('/md/add', summary='md文档项目添加', description='', )
@login_check
async def ApiProAdd(request: Request, item: dict, level=3):
    try:
        name = item.get('name')
        md_type = item.get('type')
        md_level = item.get('level')
        md_parent = item.get('parent')
        md_data = {
            "name": name,
            "type": md_type,
            "level": md_level,
            "parent": md_parent,
        }
        if MonConn.find_query('mdpro', {"name": name}):
            msg = '名称重复'
        else:
            md_data.update(
                {"date": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')})
            MonConn.insert('mdpro', md_data)
            msg = '添加成功'

        return {"status": True, "msg": msg}
    except Exception as e:
        loggers.error(e)
        return {"msg": "error", "detail": str(e), "status": False}


@router.post('/md/del', summary='任务删除', description='', )
@login_check
async def ApiProDel(request: Request, item: dict, level=2):
    try:
        datas = item.get('data')
        for i in datas:
            project = i.get('name')
            MonConn.delete_query('mdpro', {"name": project})
            MonConn.delete_query('mdData', {"task": project})
        result_list = {
            "msg": "success", "status": True
        }

        return result_list
    except Exception as e:
        loggers.error(e)
        return {"msg": "error", "status": False, "detail": str(e)}


@router.post('/md/img/upload', summary='md文档照片上传', description='', )
async def ApiImdUpload(file: UploadFile = File(...)):
    try:
        # 执行文件上传逻辑
        name = str(uuid.uuid5(uuid.NAMESPACE_DNS, str(time.time())).hex)
        contents = await file.read()
        # 保存文件到静态文件目录
        # with open(f"static/img/{name}.png", "wb") as f:
        #     f.write(contents)
        item = {"name": name,
                "img": contents}
        MonConn.insert('imgData', item)

        return {"url": f"/api/static/{name}.png"}
    except Exception as e:
        loggers.error(e)
        return {"msg": "error", "detail": str(e), "status": False}


@router.get("/static/{file_path}", summary='md文档照片展示')
async def get_uploaded_image(file_path: str):
    query = {"name": file_path.split('.')[0]}
    img_obj = MonConn.find_query('imgData', query)[0].get('img')

    return StreamingResponse(
        iter([img_obj]),
        media_type="image/jpeg"
    )


@router.post('/md/save', summary='md文档保存', description='', )
async def ApiDataSave(item: dict):
    try:
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        item.update({"date": date})
        MonConn.insert(collection, item)
        msg = '保存成功'

        return {"status": True, "msg": msg}
    except Exception as e:
        loggers.error(e)
        return {"msg": "保存失败", "detail": str(e), "status": False}


@router.post('/md/img/get', summary='md提前本地图片', description='', )
async def ApiDataSave(item: dict):
    try:
        path = './static/img/'
        tasks = item.get('task')
        img_list = []
        for task in tasks:
            task = task.split('/')[-1].split('.')[0]
            query = {"name": task}
            img_obj = MonConn.find_query('imgData', query)[0].get('img')
            encoded_data = base64.b64encode(img_obj)
            img_list.append(
                {"name": task + '.png', "data": encoded_data}
            )
        msg = '导出{}成功'.format(task)
        return {"status": True, "msg": msg, "data": img_list}
    except Exception as e:
        loggers.error(e)
        return JSONResponse(status_code=200, content={"msg": "保存失败", "detail": str(e), "status": False, "data": None})


@router.post('/md/pro/get', summary='获取任务详情', description='', )
@login_check
async def ApiGetData(request: Request, item: dict):
    try:
        task = {"task": item.get('task')}
        result = MonConn.find_query(collection, task, 'date', -1)
        result = delid(result) if result else result

        return result
    except Exception as e:
        loggers.error(e)
        return {"msg": "error", "detail": str(e)}


@router.post('/md/pro/get/all', summary='获取任务详情', description='', )
async def ApiGetDataAll(item: dict):
    try:
        task = {"task": item.get('task')}
        result = delid_list(MonConn.find_query(collection, task, 'date', -1))
        return result
    except Exception as e:
        loggers.error(e)
        return {"msg": "error", "detail": str(e)}
